package com.example.Android_test.activity.training;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.Android_test.R;
import com.example.Android_test.activity.Main;
import com.example.Android_test.helpers.SOWEngine;
import com.example.Android_test.helpers.SettingsHelper;
import com.example.Android_test.specs.WordSpec;
import com.example.Android_test.util.ReadyAnimations;

import java.util.ArrayList;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * User: anpi0413
 * Date: 21.05.13
 * Time: 11:34
 * To change this template use File | Settings | File Templates.
 */
public class Training_Pick_up_word_in_context extends  Abstract_Training {
    public static final String TITLE = "Training_Pick_up_word_in_context";
    public static int MAX_WORDS_IN_ONE_CYCLE = 5;

    private static int RIGHT_VARIANT_COLOR = Color.GREEN;
    private static int WRONG_VARIANT_COLOR = Color.RED;
    private static int ANOTHER_VARIANT_COLOR = Color.YELLOW;

    private Button puwic_button_var1;
    private Button puwic_button_var2;
    private Button puwic_button_var3;
    private Button puwic_button_var4;

    private Button puwic_button_next;
    private ImageButton puwic_imageButton_Tip;

    private TextView puwic_textView_context;
    private TextView puwic_textView_contextTranslation;

    private ProgressBar puwic_progressBar;

    private WordSpec trainingWord = null;

    private int goodCount;
    private int badCount;

    private boolean isTipUsed;

    @Override
    protected void onFirstRun() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    protected String getKeyTrainingTimeSpent() {
        return SettingsHelper.KEY_TRAINING_TIME_SPENT_PUWIC;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.training_puwic);
        setTitle(TITLE);

        try {
            if (!SOWEngine.INSTANCE.getSelectedSetOfWord().isGoodSOWForPUWICTraining()) {
              throw new Exception("Is bad SOW for PUWIC");
            }
        } catch (Exception e) {
            Log.e(Main.LOG_TAG, "Training_Pick_up_word_in_context.onCreate() error " + e.getMessage());  //To change body of catch statement use File | Settings | File Templates.
            finish();
            return;
        }

        puwic_textView_context = (TextView) findViewById(R.id.puwic_textView_context);
        puwic_textView_contextTranslation = (TextView) findViewById(R.id.puwic_textView_contextTranslation);

        puwic_progressBar = (ProgressBar) findViewById(R.id.puwic_progressBar);
        puwic_progressBar.setMax(MAX_WORDS_IN_ONE_CYCLE);
        puwic_progressBar.setProgress(0);

        puwic_button_var1 = (Button) findViewById(R.id.puwic_button_var1);
        puwic_button_var2 = (Button) findViewById(R.id.puwic_button_var2);
        puwic_button_var3 = (Button) findViewById(R.id.puwic_button_var3);
        puwic_button_var4 = (Button) findViewById(R.id.puwic_button_var4);

        puwic_button_var1.setOnClickListener(new VarButtonListener());
        puwic_button_var2.setOnClickListener(new VarButtonListener());
        puwic_button_var3.setOnClickListener(new VarButtonListener());
        puwic_button_var4.setOnClickListener(new VarButtonListener());

        puwic_button_next = (Button) findViewById(R.id.puwic_button_next);
        puwic_button_next.setOnClickListener(new NextButtonListener());

        puwic_imageButton_Tip = (ImageButton) findViewById(R.id.puwic_imageButton_tip);
        puwic_imageButton_Tip.setOnClickListener(new TipButtonListener());

        trainingStart();
    }

    @Override
    protected void trainingStart() {
        super.trainingStart();

        goodCount = 0;
        badCount = 0;

        puwic_progressBar.setProgress(0);

        next();
    }

    @Override
    protected void next() {
        prepareVariantButtons();

        puwic_textView_context.setText("");
        puwic_textView_contextTranslation.setText("");

        ReadyAnimations.animateView(this, puwic_textView_context, ReadyAnimations.ANIMATE_FADE_OUT);
        ReadyAnimations.animateView(this, puwic_textView_contextTranslation, ReadyAnimations.ANIMATE_FADE_OUT);

        ReadyAnimations.animateViewWithDelay(this, puwic_button_var1, ReadyAnimations.ANIMATE_FADE_OUT, 0);
        ReadyAnimations.animateViewWithDelay(this, puwic_button_var2, ReadyAnimations.ANIMATE_FADE_OUT, 100);
        ReadyAnimations.animateViewWithDelay(this, puwic_button_var3, ReadyAnimations.ANIMATE_FADE_OUT, 200);
        ReadyAnimations.animateViewWithDelay(this, puwic_button_var4, ReadyAnimations.ANIMATE_FADE_OUT, 300);

        try {
            trainingWord = SOWEngine.INSTANCE.getWordToTraining();
        } catch (Exception e) {
            Log.e(Main.LOG_TAG, "Training_Pick_up_word_in_context.next() error" + e.getMessage());
            return;
        }


        ArrayList<WordSpec> randWords;
        try {
            randWords = SOWEngine.INSTANCE.getRandomWords(trainingWord, 3);
        } catch (Exception e) {
            Log.e(Main.LOG_TAG, e.getMessage());
            return;
        }

        randWords.add(trainingWord);
        Random rand = new Random();
        for (int i=0; i < 4; i++) {
            int randNum = rand.nextInt(randWords.size());

            switch (i) {
                case 0: puwic_button_var1.setText(randWords.get(randNum).getWord());
                    break;
                case 1: puwic_button_var2.setText(randWords.get(randNum).getWord());
                    break;
                case 2: puwic_button_var3.setText(randWords.get(randNum).getWord());
                    break;
                case 3: puwic_button_var4.setText(randWords.get(randNum).getWord());
                    break;
                default: break;
            }

            randWords.remove(randNum);
        }

        puwic_textView_context.setText(Html.fromHtml(replaceTagBWithStars(trainingWord.getInContext())));
        puwic_textView_contextTranslation.setText(Html.fromHtml(replaceTagBWithStars(trainingWord.getInContextTranslation())));

        puwic_button_next.setVisibility(View.GONE);
        puwic_imageButton_Tip.setVisibility(View.VISIBLE);

        isTipUsed = false;
    }

    private String replaceTagBWithStars(String str) {
        String result = "";
        while (str.contains("<b>")) {
            result += str.substring(0, str.indexOf("<b>") + "<b>".length());
            str = str.substring(str.indexOf("<b>") + "<b>".length());

            result += "***";

            result += str.substring(str.indexOf("</b>"));
            str = str.substring(str.indexOf("</b>"));
        }

        return result;
    }

    private String prepareContext(WordSpec word) {
        //String result = word.getInContext().replace(word.getWord(), "***");
        String result = word.getInContext().replaceAll("(?i)"+word.getWord(), "***");
        return result;
    }

    private String prepareContextTranslation(WordSpec word) {
        //String result = word.getInContextTranslation().replace(word.getTranslationVariantSpecs().get(0).getTranslate(), "***");
        String result = word.getInContextTranslation().replaceAll("(?i)"+word.getTranslationVariantSpecs().get(0).getTranslate(), "***");
        return result;
    }

    private void prepareVariantButtons() {
        puwic_button_var1.setBackgroundResource(R.drawable.button_custom);
        puwic_button_var2.setBackgroundResource(R.drawable.button_custom);
        puwic_button_var3.setBackgroundResource(R.drawable.button_custom);
        puwic_button_var4.setBackgroundResource(R.drawable.button_custom);

        enableAllVariantButtons();
    }

    private void enableAllVariantButtons() {
        puwic_button_var1.setEnabled(true);
        puwic_button_var2.setEnabled(true);
        puwic_button_var3.setEnabled(true);
        puwic_button_var4.setEnabled(true);
    }

    private void disableAllVariantButtons() {
        puwic_button_var1.setEnabled(false);
        puwic_button_var2.setEnabled(false);
        puwic_button_var3.setEnabled(false);
        puwic_button_var4.setEnabled(false);
    }

    private void alertOnFinish() {
        String result = String.format(getResources().getString(R.string.training_etr_result), goodCount, goodCount+badCount);

        AlertDialog dialog = new AlertDialog.Builder(this).setMessage(result)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(Main.getAppContext(), "PositiveButton", Toast.LENGTH_LONG).show();
                        dialog.dismiss();

                        puwic_progressBar.setProgress(0);
                        trainingStart();
                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(Main.getAppContext(), "NegativeButton", Toast.LENGTH_LONG).show();
                        dialog.dismiss();

                        finish();
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface dialog) {
                        //Toast.makeText(Main.getAppContext(), "onCancel", Toast.LENGTH_LONG).show();
                        dialog.dismiss();

                        finish();
                    }
                }).create();

        dialog.show();

        /*AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Reset...");
        alertDialog.setMessage("Are you sure?");
        //alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new AlertDialogButtonOKListener());
        // alertDialog.setIcon(R.drawable.icon);
        alertDialog.show();*/
    }


    private class VarButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Button clickedButton = (Button) v;

            if (clickedButton.getText().equals(trainingWord.getWord())) {
                disableAllVariantButtons();

                clickedButton.setBackgroundColor(RIGHT_VARIANT_COLOR);
                trainingWord.setRating(trainingWord.getRating() + 1);
                trainingWord.setShowed(trainingWord.getShowed() + 1);

                playSound(trainingWord.getSoundResName());

                goodCount++;
            } else {
                clickedButton.setBackgroundColor(WRONG_VARIANT_COLOR);

                if (puwic_button_var1.getText().equals(trainingWord.getWord())) puwic_button_var1.setBackgroundColor(ANOTHER_VARIANT_COLOR);
                if (puwic_button_var2.getText().equals(trainingWord.getWord())) puwic_button_var2.setBackgroundColor(ANOTHER_VARIANT_COLOR);
                if (puwic_button_var3.getText().equals(trainingWord.getWord())) puwic_button_var3.setBackgroundColor(ANOTHER_VARIANT_COLOR);
                if (puwic_button_var4.getText().equals(trainingWord.getWord())) puwic_button_var4.setBackgroundColor(ANOTHER_VARIANT_COLOR);

                disableAllVariantButtons();

                trainingWord.setRating(trainingWord.getRating() - 1);

                badCount++;
            }
            SOWEngine.INSTANCE.saveCurrentSetOfWords();

            puwic_textView_context.setText(trainingWord.getInContext());
            puwic_textView_contextTranslation.setText(trainingWord.getInContextTranslation());

            puwic_progressBar.setProgress(puwic_progressBar.getProgress() + 1);
            if (puwic_progressBar.getProgress() >= MAX_WORDS_IN_ONE_CYCLE) { // its are finish
                alertOnFinish();

            } else { // next training step
                puwic_button_next.setVisibility(View.VISIBLE);
                puwic_imageButton_Tip.setVisibility(View.GONE);
                ReadyAnimations.animateView(getBaseContext(), puwic_button_next, ReadyAnimations.ANIMATE_RIGHT_GO_GO);
            }
        }
    }

    private class NextButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            next();
        }
    }

    private class TipButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            isTipUsed = true;

            puwic_button_next.setVisibility(View.VISIBLE);
            puwic_imageButton_Tip.setVisibility(View.GONE);
        }
    }
}